package com.guagua.chat.top;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONUtils;

import me.prettyprint.cassandra.model.ConfigurableConsistencyLevel;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.cassandra.service.CassandraHostConfigurator;
import me.prettyprint.cassandra.service.FailoverPolicy;
import me.prettyprint.cassandra.service.template.ColumnFamilyResult;
import me.prettyprint.cassandra.service.template.ColumnFamilyTemplate;
import me.prettyprint.cassandra.service.template.ThriftColumnFamilyTemplate;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.HConsistencyLevel;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.exceptions.HectorException;
import me.prettyprint.hector.api.factory.HFactory;

import com.guagua.chat.base.BaseAction;
import com.guagua.user.UserManager;
import com.guagua.user.UserManagerConfig;
import com.guagua.vas.constants.ConfigConstants;



public class TopAction extends BaseAction{
    private String roomId;
    private String allottedTime;//"day,week,month";
    private String type;//contribution(贡献) popularity(红人)
    private TopDao topDao = new TopDao();
    
    public String queryTop5(){
    	String data = null;
    	if(type.equals("popularity")){//红人榜
    		if(allottedTime.equals("day")){
    			data = topDao.getPopularityDAY(roomId);
    		}else if(allottedTime.equals("week")){
    			data = topDao.getPopularityWeek(roomId);
    		}else if(allottedTime.equals("month")){
    			data = topDao.getPopularityMonth(roomId);
    		}
    	}else if(type.equals("contribution")){//贡献榜
    		if(allottedTime.equals("day")){
    			data = topDao.getContributionDAY(roomId);
    		}else if(allottedTime.equals("week")){
    			data = topDao.getContributionWeek(roomId);
    		}else if(allottedTime.equals("month")){
    			data = topDao.getContributionMonth(roomId);
    		}
    	}
    	String[] userIdList = new String[0];
    	if(data!=null && !(data=data.trim()).equals("")){
    		userIdList = data.split(",");
    	}
    	ArrayList<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
        int row=0;
    	for(String userId : userIdList){
    		Map<String,Object> map = new HashMap<String,Object>();
    		map.put("userId", userId);
    		try {
				map.put("nickname", UserManager.getInstance().getNickname(Long.parseLong(userId)));
			} catch (NumberFormatException e) {
				map.put("nickname", "");
				e.printStackTrace();
			} catch (Exception e) {
				map.put("nickname", "");
				e.printStackTrace();
			}
    		resultList.add(map);
    		row++;
    		if(row ==5){
    			break;
    		}
    	}
    	Map resultMap = new HashMap();
    	resultMap.put("allottedTime", allottedTime);
    	resultMap.put("type", type);
    	resultMap.put("resultData", resultList);
    	String json = JSONObject.fromObject(resultMap).toString();
    	response.setHeader("Content-type", "application/json");
		response.setHeader("Cache-Control","no-cache");
		response.setHeader("expires", "-1");
		try {
			response.getWriter().write(json);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
    	return null;
    }
    public String query() throws Exception{
    	String data = null;
    	if(type.equals("popularity")){//红人榜
    		if(allottedTime.equals("day")){
    			data = topDao.getPopularityDAY(roomId);
    		}else if(allottedTime.equals("week")){
    			data = topDao.getPopularityWeek(roomId);
    		}else if(allottedTime.equals("month")){
    			data = topDao.getPopularityMonth(roomId);
    		}
    	}else if(type.equals("contribution")){//贡献榜
    		if(allottedTime.equals("day")){
    			data = topDao.getContributionDAY(roomId);
    		}else if(allottedTime.equals("week")){
    			data = topDao.getContributionWeek(roomId);
    		}else if(allottedTime.equals("month")){
    			data = topDao.getContributionMonth(roomId);
    		}
    	}
    	String[] userIdList = new String[0];
    	if(data!=null && !(data=data.trim()).equals("")){
    		userIdList = data.split(",");
    	}
    	ArrayList<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
    	for(String userId : userIdList){
    		Map<String,Object> map = new HashMap<String,Object>();
    		map.put("userId", userId);
    		System.out.println("userId == "+userId);
//    		map.put("nickname", "lllyyy");
    		map.put("nickname", UserManager.getInstance().getNickname(Long.parseLong(userId)));
    		resultList.add(map);
    	}
    	Map resultMap = new HashMap();
    	resultMap.put("allottedTime", allottedTime);
    	resultMap.put("type", type);
    	resultMap.put("resultData", resultList);
    	String json = JSONObject.fromObject(resultMap).toString();
    	response.setHeader("Content-type", "application/json");
		response.setHeader("Cache-Control","no-cache");
		response.setHeader("expires", "-1");
		response.getWriter().write(json);
		
    	return null;
    }
    
    
	public String queryZhouInfo() {

		String keySpace = ConfigConstants.CASSANDRA_KEYSPACE;// 相当于DB NAME
		String columnFamily = ConfigConstants.CASSANDRA_COLUMNFAMILY;// 相当于DB Table
		 CassandraHostConfigurator chc = new CassandraHostConfigurator();
		  chc.setHosts(ConfigConstants.CASSANDRA_IP_PORT);//auto-failover
		Cluster cluster = HFactory.getOrCreateCluster(ConfigConstants.CASSANDRA_CLUSTERNAME, chc);
		 ConfigurableConsistencyLevel ccl = new ConfigurableConsistencyLevel();
	        ccl.setDefaultReadConsistencyLevel(HConsistencyLevel.LOCAL_QUORUM);
		Map accessMap = new HashMap();
		accessMap.put("username", ConfigConstants.CASSANDRA_USERNAME);
		accessMap.put("password", ConfigConstants.CASSANDRA_PASSWORD);
		Keyspace ksp = HFactory.createKeyspace(keySpace, cluster, ccl, FailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE, accessMap);
		ColumnFamilyTemplate<String, String> template = new ThriftColumnFamilyTemplate<String, String>(ksp, columnFamily, StringSerializer.get(), StringSerializer.get());
		try {
			ColumnFamilyResult<String, String> res = template.queryColumns(roomId);
			String result = res.getString("result");
			try {
				response.getWriter().write("{flag:1,content:"+result+"}");
			}
			catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		} catch (HectorException e) {
			try {
				e.printStackTrace();
				response.getWriter().write("{flag:0,content:[]}");
			}
			catch (IOException e1) {
				e1.printStackTrace();
			}
			return null;
		}
	}

    
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getAllottedTime() {
		return allottedTime;
	}
	public void setAllottedTime(String allottedTime) {
		this.allottedTime = allottedTime;
	}
	public String getRoomId() {
		return roomId;
	}

	public void setRoomId(String roomId) {
		this.roomId = roomId;
	}
	
	
	public static void main(String[] args) throws Exception{
     System.out.println(UserManager.getInstance().getNickname(35491795L));
	}
	
}
